import { type InformationCategoryItem } from '@/api/dynamicAllocation/types';
import { memberApply } from '@/api/membership';
import { ConfigRouterTypeEnum } from '@/enums/configRouterTypeEnum';
import { DynamicTabbarPagesEnum, TabbarPageEnum } from '@/enums/pageEnum';
import { navigateTo, getUrl, redirectTo, switchTab, getUrlName, ParsingUrlParams } from '@/router';
import { type QueryType } from '@/router/types';
import { type PagesType } from '@/router/types/pages';
import { Toast } from '..';
import { isObject, isLogin } from '../is';
import { IsFinishEnum, PaymentStatusEnum, MemberOrderType } from '@/enums/membershipEnum';
import { useEnv } from '@/hooks/core/useEnv';
import { addAppShareLog, getMallSecretKeyApi, miniProgramCode } from '@/api';
import { ThridTypeEnum } from '@/enums/loginEnum';
import { useAppStoreWithOut } from '@/store/modules/app';
import { useUserStoreWithOut } from '@/store/modules/user';

interface Options {
  id?: string | number;
  title?: string;
  pageTitle?: string
  linkUrl?: string;
  categoryList?: InformationCategoryItem[];
  /** 封面图 */
  coverUrl?: string;
  /** 公众号文章链接 */
  officialAccountsLink?: string;
  /** 是否使用redirectTo跳转 */
  isRedirectTo?: boolean;
  /** 跳转小程序的 appId */
  appId?: string;
}
export function parseConfigRouter(type: ConfigRouterTypeEnum, options: Options) {
  const { id, linkUrl, officialAccountsLink } = options;
  const { cocInfo } = useUserStoreWithOut()
  const { tabbarList, globalConfig } = useAppStoreWithOut()

  switch (type) {
    case ConfigRouterTypeEnum.CATEGORY:
      toInformationType(options);
      break;
    case ConfigRouterTypeEnum.INFODETAILS:
      if (officialAccountsLink) {
        navigateTo({ name: 'weChatOfficialAccountLink', options: { id } });
      } else {
        navigateTo({ name: 'richDetails', options: { id, pageTitle: '文章详情' } });
      }
      break;
    case ConfigRouterTypeEnum.ACTIVITY_DETAILS:
      id && navigateTo({ name: 'activityDetails', options: { id: Number(id) } });
      break;
    case ConfigRouterTypeEnum.SYSTEM_LINK:
      if (options.linkUrl === 'welcomeMember' && !cocInfo) {
        toSelectiveType({ ...options, linkUrl: 'selectiveType' })
        return
      }
      if (options.linkUrl === 'selectiveType') {
        toSelectiveType(options);
        return
      }
      /** 系统链接配置在Tabbar中时, 跳转Tabbar页 */
      const tabbarItem = tabbarList.find(v => v.component === options.linkUrl)
      if (tabbarItem) {
        switchTab(tabbarItem.pagePath as any)
        return
      }
      navigateTo({ name: linkUrl as any, options: { id } }).catch(() => Toast('暂无关联内容'));
      break;
    case ConfigRouterTypeEnum.PHOTOALBUM_DETAILS:
      id && navigateTo({ name: 'photoAlbumDetails', options: { id: Number(id) } });
      break;
    case ConfigRouterTypeEnum.MINI_PROGRAM:
      navigateToMiniProgram(options.appId as string, options.linkUrl);
      break;
    case ConfigRouterTypeEnum.WEBVIEW:
      options.linkUrl
        ? navigateTo({
          name: 'webview', options: {
            url: options.linkUrl,
          }
        })
        : Toast('暂无关联内容');
      break;
    case ConfigRouterTypeEnum.ACTIVITY_LIST:
      const item = tabbarList.find(v => v.component === DynamicTabbarPagesEnum.BASE_ACTIVITY)
      item ? switchTab(item.pagePath as any) : navigateTo({ name: 'activity', options: {} })
      break;
    case ConfigRouterTypeEnum.ALBUM_LIST:
      navigateTo({ name: 'photoAlbumManage' })
      break;
    case ConfigRouterTypeEnum.CLOUD_HOME:
      toHuibangCloud('storeHome', { type: 'home' })
      break;
    case ConfigRouterTypeEnum.AI_MINI_PROGRAM:
      toAIminiProgram('aiChatPage')
      break;
    case ConfigRouterTypeEnum.INTERNAL_LINKS:
      analyzeInternalLinks(options.linkUrl)
      break;
    default:
      Toast('暂无关联内容');
  }
}

/**
 * @description 跳转资讯分类
 * @date 28/07/2022
 * @export
 * @param {Options['categoryList']} options
 */
export function toInformationType(options: Options) {
  const { categoryList, title, pageTitle } = options;
  if (!categoryList || categoryList?.length === 0) return Toast('配置错误, 请检查配置!');
  let moduleCode = categoryList[0].id;
  let childrens = categoryList.filter((v) => {
    if (v.level === 1) {
      moduleCode = v.id;
      return false;
    }
    return v.level === 2;
  });
  navigateTo({
    name: 'informationType', options: {
      moduleCode,
      childrens,
      subTitle: title,
      pageTitle: pageTitle
    }
  });
}

/**
 * @description 跳转入会申请
 * @date 10/10/2022
 * @export
 */
export function toSelectiveType(options: Options, callback?: () => void, isBackHome?: boolean): void {
  const backFnc = (name: any, op?: any) => {
    return options.isRedirectTo ? redirectTo({ name, options: op }) : navigateTo({ name, options: op });
  }
  const isApply = function () {
    // 跳转去入会申请前,查询我的申请状态
    memberApply().then((r) => {
      // 存在申请资料
      if (r) {
        const { isFinish, paymentStatus, applyTemplateId, id, formStageId } = r;
        if (
          Number(isFinish) === IsFinishEnum.DONE &&
          Number(paymentStatus) === PaymentStatusEnum.NOTPAYCOST
        ) {
          // 申请流程已走完,并且未缴费,跳转去缴费页面
          backFnc('awaitPay', { type: MemberOrderType.PAYFEES, id, formStageId });
        } else if (
          Number(isFinish) === IsFinishEnum.DONE &&
          Number(paymentStatus) === PaymentStatusEnum.DUE
        ) {
          // 申请流程已走完,并且在缴费审核中
          backFnc('awaitPay', { type: MemberOrderType.PAYFEES, id, formStageId });
        } else if (
          Number(isFinish) === IsFinishEnum.DONE &&
          Number(paymentStatus) === PaymentStatusEnum.ALREADYPAYCOST
        ) {
          // 申请流程已走完,并且已缴费,跳转会员证
          backFnc('welcomeMember');
        } else {
          backFnc('membershipInfo', {
            id: applyTemplateId,
          });
        }
      } else {
        if (!options.id && !options.linkUrl) {
          callback?.();
          return;
        }
        // 不存在入会资料,则正常跳转
        backFnc(options.linkUrl as any, {}).catch(() => Toast('暂无关联内容'));
      }
    });
  };
  isLogin(() => isApply(), isBackHome);
}

/**
 * @description 创建小程序二维码
 * @date 18/10/2022
 * @export
 * @param {{ path: PagesType; query: Recordable }} data
 */
export async function createMiniCode(data: { path?: PagesType; query?: Recordable, shareLogId?: number }): Promise<string> {
  const { path, query } = data;
  let shareLogId = data.shareLogId
  try {
    // 获取小程序码
    const { envVersion } = useEnv();
    if (path && !shareLogId) {
      const { id } = await addAppShareLog({
        path: getUrl(path),
        query: JSON.stringify(query),
      });
      shareLogId = id
    }
    return await miniProgramCode({
      scene: shareLogId!.toString(),
      page: getUrl('startPage'),
      tripartiteName: 'mini_yjr',
      thridType: ThridTypeEnum.WX3RD,
      env_version: envVersion,
      check_path: true,
    });
  } catch (error) {
    console.error(error);
    return '';
  }
}

/**
 * @description 跳转小程序
 * @date 06/01/2023
 * @export
 * @param {string} [appId] 目标小程序appid
 * @param {string} [path] 目标小程序路径
 */
export function navigateToMiniProgram(appId: string, path?: string, extraData?: Recordable) {
  const isShortLink = path?.includes('#小程序')
  if (!appId && !isShortLink) return Toast('暂无关联内容');
  const { envVersion } = useEnv();
  let data: UniApp.NavigateToMiniProgramOptions = {
    appId,
    path,
    envVersion,
    extraData
  };
  if (isShortLink) {
    data.shortLink = data.path;
    delete data.path
  }
  uni.navigateToMiniProgram({
    ...data,
    success: () => console.log('跳转成功'),
    fail: (err: any) => console.error(err),
  } as any);
}

type HuibangCloudPageType = 'storeHome' | 'goodsDetail'
/**
 * @description 跳转会邦云机构商城
 * @date 17/11/2023
 * @export
 * @param {HuibangCloudPageType} path
 * @param {Recordable} query
 */
export async function toHuibangCloud(path: HuibangCloudPageType = 'storeHome', query?: Recordable) {
  const { globalConfig } = useAppStoreWithOut()
  const secretKey = await getMallSecretKeyApi();
  navigateToMiniProgram(globalConfig?.mallAppId as string, 'pages/base/startPage/main', {
    secretKey,
    path,
    query,
  });
}

type AIminiProgramPageType = 'home' | 'aiChatPage'
/**
 * @description 跳转AI小程序
 * @date 24/03/2025
 * @export
 * @param {string} path
 * @param {Recordable} query
 */
export function toAIminiProgram(path: AIminiProgramPageType = 'home', query?: Recordable) {
  const { globalConfig } = useAppStoreWithOut()
  query = query || {}
  if (path === 'aiChatPage' && !query?.uuid) {
    query.uuid = globalConfig?.aiBotUUID
  }
  navigateToMiniProgram(globalConfig?.aiAppId as string, 'pages/base/startPage/main', {
    path,
    query,
  });
}


/**
 * @description 解析系统链接
 * @date 30/08/2024
 * @export
 * @param {string} linkUrl
 */
export function analyzeInternalLinks(linkUrl?: string) {
  if (!linkUrl) return Toast('内部链接为空')
  const [url, query] = linkUrl.split('?')
  const routerName = getUrlName(url)
  let routerOptions: Recordable = {}
  if (!routerName) return Toast('链接错误')
  if (query) {
    query.split('&').forEach(item => {
      const [key, value] = item.split('=')
      routerOptions[key] = value
    })
    routerOptions = ParsingUrlParams(routerOptions) || {}
  }

  navigateTo({ name: routerName as any, options: routerOptions })
}